<?php
/**
 * 参数处理类
 */
namespace Hi;

class Params {

    /**
     * Params Instance
     * @var
     */
    protected static $_instance;

    /**
     * 参数数组
     * @var array
     */
    public $_params = array();

    /**
     * POST数组
     * @var array
     */
    public $_post = array();

    /**
     * GET数组
     * @var array
     */
    public $_get = array();

    /**
     * 获取实例
     * @return Params
     */
    public static function getInstance() {
        if (self::$_instance === NULL) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * 构造
     * Params constructor.
     */
    protected function __construct() {
        if (!empty($_GET)) {
            foreach ($_GET as $key => $val) {
                if (is_array($val)) {
                    $this->_get[$key] = $this->getArray($val);
                } else {
                    if (is_int($val)) {
                        $this->_get[$key] = $this->getInt($val);
                    } else {
                        $this->_get[$key] = $this->getStr($val);
                    }
                }
            }
        }

        if (!empty($_POST)) {
            foreach ($_POST as $key => $val){
                if (is_array($val)) {
                    $this->_post[$key] = $this->getArray($val);
                } else {
                    if (is_int($val)) {
                        $this->_post[$key] = $this->getInt($val);
                    } else {
                        $this->_post[$key] = $this->getStr($val);
                    }
                }
            }
        }
    }

    /**
     * 获得一个整型变量
     * @param $number
     * @return int
     */
    private function getInt($number) {
        return intval($number);
    }

    /**
     * 返回一个字符型变量
     * @param $string
     * @return string
     */
    private function getStr($string) {
        if (!function_exists("get_magic_quotes_gpc") || !get_magic_quotes_gpc()) {
            $string = addslashes($string);
        }
        return $string;
    }

    /**
     * 递归方式过滤数组
     * @param $array
     * @return mixed
     */
    private function getArray($array) {
        foreach ($array as $key => $val) {
            if (is_array($val)) {
                $array[$key] = $this->getArray($val);
            } else {
                if (is_int($val)) {
                    $array[$key] = $this->getInt($val);
                } else {
                    $array[$key] = $this->getStr($val);
                }
            }
        }
        return $array;
    }

    public function setParams(array $params) {
        $this->_params = $this->_params + (array) $params;

        foreach ($params as $key => $value) {
            if ($value === NULL) {
                unset($this->_params[$key]);
            }
        }
        return;
    }
}